<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
      <!-- <el-breadcrumb-item><a href="/">活动管理</a></el-breadcrumb-item> -->
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-input
            clearable
            @clear="getUserList"
            placeholder="请输入内容"
            v-model="queryinfo.query"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-button type="primary" @click="addLogVisible = true">添加</el-button>
        <el-col :span="2"></el-col>
      </el-row>

      <!-- 表格 -->
      <el-table :data="userlist" style="width: 100%" stripe border>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scop">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="mini"
              @click="showEditLog(scop.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click="deleteUser(scop.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                size="mini"
                @click="showRight(scop.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 5, 8, 10]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total"
      >
      </el-pagination>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addLogVisible"
      width="30%"
      @close="addLogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addLogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editLogVisible"
      width="50%"
      @close="editFormClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormrules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editLogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限对话框 -->

    <el-dialog title="提示" :visible.sync="rightLogVisible" width="30%">
      <pre>当前的用户:{{ role.username }}</pre>
      <pre>当前的角色:{{ role.role_name }}</pre>

      <el-select v-model="selectRole" placeholder="请选择">
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rightLogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRightRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 修改
      editLogVisible: false,
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      addLogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入电话', trigger: 'blur' }],
      },
      editFormrules: {
        mobile: { required: true, message: '请输入电话', trigger: 'blur' },
        email: { required: true, message: '请输入邮箱', trigger: 'blur' },
      },
      editForm: {},
      rightLogVisible: false,
      role: {},
      // 所有角色的数据列表
      roleList: [],
      selectRole: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryinfo,
      })
      if (res.meta.status !== 200) {
        return this.$messeage.error('获取用户列表失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryinfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      console.log(newPage)
    },
    async userStateChanged(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$Message.error('更新用户状态失败!')
      }
      this.$Message.success('更新用户状态成功!')
    },
    addLogClose() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)

        if (res.meta.status !== 201) {
          this.$Message.error('添加失败')
        }
        this.$Message.success('添加成功')

        this.addLogVisible = false

        this.getUserList()
      })
    },

    // 展示修改对话框
    async showEditLog(id) {
      const { data: res } = await this.$http.get('users/' + id)

      this.editForm = res.data
      this.editLogVisible = true
    },
    // 修改重置
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改预验证
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        if (res.meta.status !== 200) {
          return this.$Message.error('修改失败')
        }
        this.$Message.success('修改成功')
        //  刷新数据
        this.getUserList()
        //  关闭对话框
        this.editLogVisible = false
      })
    },
    async deleteUser(id) {
      const comfirmRes = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (comfirmRes !== 'confirm') {
        return this.$Message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)

      if (res.meta.status != 200) {
        return this.$Message.error('删除失败')
      }

      this.$Message.success('删除成功')

      this.getUserList()
    },
    // 权限修改
    async showRight(role) {
      this.rightLogVisible = true

      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) this.$Message.error('获取角色失败')

      this.roleList = res.data

      this.role = role
    },
    async saveRightRole() {
      if (!this.selectRole) {
        return this.$Message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.role.id}/role`, {
        rid: this.selectRole,
      })
      // console.log(this.selectRole);
      if (res.meta.status !== 200) return this.$Message.error('请求失败')
      this.$Message.success('更新成功')
      this.getUserList()
      this.rightLogVisible = false
    },
  },
}
</script>

<style scoped>
.box-card {
  margin-top: 20px;
  box-shadow: 0, 1px, 1px, rgba(0, 0, 0, 0.15) !important;
}
.el-table {
  font-size: 12px;
  margin-top: 12px;
}
</style>